// pages/profile/personalization/index.ts
import tran from "../../../utils/language";
import { debounce } from "../../../utils/index.js";
import {
    userInfoStepTwo,
    uploadFile,
    userList,
    presignedUrl,
} from "../../../utils/api";
Page({
    /**
     * 页面的初始数据
     */
    data: {
        _t: tran._t("personalization"),
        _tBase: tran._t("base"),
        showToOthers: false,
        nextTapFlag: false,
        // picArr: ['', '', '', '', '', 'https://res.wx.qq.com/wxdoc/dist/assets/img/0.4cb08bb4.jpg'],
        picArr: ["", "", "", "", "", ""],
        showToOthersPopup: false,
        isEdit: getApp().globalData.profileFrom === "edit",
        formData: {
            bio: "",
            photos: [],
            onlyPublicAvatar: false,
        },
        picAll: [0, 1, 2, 3, 4, 5],
        registerFlag: "",
        textNum: 0,
        currentPicIndex: 0,
        canvasFlag: false,
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options: any) {
        console.log(options, "这里");
        const loginInfo = wx.getStorageSync("userInfo");
        let { formData, picArr } = this.data;
        formData.bio = loginInfo.bio;
        formData.photos = loginInfo.photos;
        formData.onlyPublicAvatar = loginInfo.onlyPublicAvatar || false;
        const picList = loginInfo.photos;
        // 固定的6个图片
        let list = [0, 1, 2, 3, 4, 5];
        if (picList && picList.length > 0) {
            for (let i = 0; i < 6; i++) {
                if (picList[i]) {
                    list[i] = picList[i];
                    picArr[i] = picList[i];
                } else {
                    list[i] = i;
                }
            }
        }
        this.setData(
            {
                formData,
                picAll: list,
                picArr,
                registerFlag: options.type,
                textNum: formData.bio ? formData.bio.length : 0,
            },
            () => {
                this.checkNextTapFlag();
            }
        );
    },
    checkNextTapFlag() {
        const { bio } = this.data.formData;
        const { picArr } = this.data;
        const list = picArr.filter((item) => item != "");
        console.log("走这里", picArr, list);
        if (bio && list.length > 0) {
            this.setData({
                nextTapFlag: true,
            });
        } else {
            this.setData({
                nextTapFlag: false,
            });
        }
    },
    changeVisible() {
        const { formData } = this.data;
        formData.onlyPublicAvatar = !this.data.formData.onlyPublicAvatar;
        this.setData({ formData });
    },
    nextTap() {
        const { bio, onlyPublicAvatar } = this.data.formData;
        const { picArr, registerFlag } = this.data;
        const list = picArr.filter((item) => item != "");
        if (list.length < 1) {
            wx.showToast({
                title: "最少上传1张图片",
                icon: "none",
            });
            return false;
        }
        const params = {
            bio,
            photos: list,
            onlyPublicAvatar,
        };
        this.setData({
            nextTapFlag: false,
        });
        userInfoStepTwo(params).then((res) => {
            // 因为请求里面都判断了状态码，所以走到这里，就是成功了
            // wx.showToast({
            //   title: '操作成功'
            // })
            let loginInfo = wx.getStorageSync("loginInfo");
            if (loginInfo.completedStep <= 2) {
                loginInfo.completedStep = 2;
                wx.setStorageSync("loginInfo", loginInfo);
            }
            // 判断不是注册
            if (registerFlag != "register") {
                getApp().getUserInfo();
            }
            wx.navigateTo({
                url: `/pages/profile/interests-skills/index?type=${registerFlag}`,
            });
            setTimeout(() => {
                this.setData({
                    nextTapFlag: true,
                });
            }, 1000);
        });
    },
    previousTap() {
        // wx.navigateBack()
        wx.navigateTo({
            url: "/pages/profile/create-account/index?type=register",
        });
    },
    /**
     * 使用防抖
     */
    // textareaChange: debounce(function (e: any) {
    //   let value = e[0].detail.value
    //   const { formData } = this.data
    //   formData.bio = value
    //   this.setData({
    //     formData,
    //     textNum: value.length || 0
    //   }, () => {
    //     this.checkNextTapFlag()
    //   })
    // }, 300),
    textareaChange(e: any) {
        let value = e.detail.value;
        const { formData } = this.data;
        formData.bio = value;
        this.setData(
            {
                formData,
                textNum: value.length || 0,
            },
            () => {
                this.checkNextTapFlag();
            }
        );
    },
    uploadPic(e: baseEvent) {
        const that = this;
        const index = e.currentTarget.dataset.index;
        this.setData({
            currentPicIndex: index,
        });
        const { picAll } = this.data;
        wx.chooseMedia({
            count: 9,
            mediaType: ["image", "video"],
            sourceType: ["album", "camera"],
            maxDuration: 30,
            camera: "back",
            success(res) {
                console.log(res, "这里类型");
                // 以下是上传图片到我们服务器的代码
                const fileTypeList = res.tempFiles[0].tempFilePath.split(".");
                const fileType =
                    fileTypeList.length > 1 ? `.${fileTypeList[1]}` : ".png";
                const fileSize = res.tempFiles[0].size;
                // 检查文件大小（例如，限制最大为 5MB）
                const maxSize = 5 * 1024 * 1024; // 5MB
                if (fileSize > maxSize) {
                    wx.showToast({
                        title: "图片大小超过5MB",
                        icon: "none",
                    });
                    return false;
                }
                console.log(fileType);
                const allowedTypes = [".jpeg", ".jpg", ".png"];
                if (!allowedTypes.includes(fileType)) {
                    wx.showToast({
                        title: "只支持jpeg、jpg、png格式的图片",
                        icon: "none",
                    });
                    return false;
                }
                // that.cropImage(res, res.tempFiles[0].tempFilePath);
                wx.cropImage({
                    src: res.tempFiles[0].tempFilePath, // 图片路径
                    cropScale: "3:4", // 裁剪比例
                    success: function (res5) {
                        console.log(res5);
                        that.uploadIntFn(res, res5);
                    },
                });
                // const image = wx.createImage()
                // image.src = res.tempFiles[0].tempFilePath
                // image.onload = function () {
                //   console.log(image, '图片信息');
                //   const width = image.width
                //   const height = image.height
                //   const maxWidth = 1024
                //   const maxHeight = 1024
                //   if (width > maxWidth || height > maxHeight) {
                //     wx.showToast({
                //       title: '图片尺寸超过1024x1024',
                //       icon: 'none'
                //     })
                //     return
                //   }
                // }
            },
        });
    },
    cropImage(oldObj: any, imagePath: string) {
        console.log("走这里", imagePath);
        this.setData({
            canvasFlag: true,
        });
        const ctx = wx.createCanvasContext("myCanvas");
        const devicePixelRatio = wx.getSystemInfoSync().pixelRatio;
        console.log(devicePixelRatio, "像素比");
        const canvasWidth = 335;
        const canvasHeight = 360;
        const that = this;
        console.log("走这里1", ctx);
        ctx.drawImage(imagePath, 0, 0, canvasWidth, canvasHeight);
        // 裁剪图片到中间部分
        // const cropSize = 1260; // 裁剪区域大小
        // const cropSize = 1260; // 裁剪区域大小
        const cropSize = 1360; // 裁剪区域大小

        // const cropX = (canvasWidth - cropSize) / 2;
        // const cropY = (canvasHeight - cropSize) / 2;
        const cropX = (cropSize - canvasWidth) / 2;
        const cropY = (cropSize - canvasHeight) / 2;
        console.log("走这里12", ctx);
        // drawImage(所要绘制的图片资源；图片剪裁选择框的左上角x坐标；图片剪裁选择框的左上角y坐标；图片剪裁选择框的宽度；图片剪裁选择框的高度；图片的左上角在目标canvas上x轴的位置；图片的的左上角在目标canvas上y轴的位置；在目标画布上绘制图片的宽度 允许对绘制的图片进行缩放；在目标画布上绘制图片的高度 允许对绘制的图片进行缩放)
        // ctx.drawImage(imagePath, cropX, cropY, cropSize, cropSize, 0, 0, canvasWidth, canvasHeight);
        // ctx.drawImage(imagePath, 100, 200, cropSize, cropSize, 0, 0, canvasWidth, canvasHeight);
        ctx.drawImage(
            imagePath,
            60,
            300,
            cropSize,
            cropSize,
            0,
            0,
            canvasWidth,
            canvasHeight
        );
        console.log("走这里123", ctx);
        // 绘制到 canvas
        setTimeout(() => {
            ctx.draw(false, () => {
                console.log("走这里122", ctx);
                // 将 canvas 内容导出为图片
                wx.canvasToTempFilePath({
                    x: 0,
                    y: 0,
                    width: canvasWidth,
                    height: canvasHeight,
                    destWidth: canvasWidth,
                    destHeight: canvasHeight,
                    canvasId: "myCanvas",
                    success: (res) => {
                        console.log("裁剪的", res);
                        // this.setData({
                        //   croppedImagePath: res.tempFilePath,
                        // });
                        that.uploadIntFn(oldObj, res);
                    },
                    fail: (err) => {
                        console.error("裁剪图片失败", err);
                    },
                });
            });
        }, 500);
    },
    async uploadIntFn(oldObj: any, canvasObj: any) {
        this.setData({
            canvasFlag: false,
        });
        console.log(canvasObj);
        // 以下是上传图片到我们服务器的代码
        const fileTypeList = oldObj.tempFiles[0].tempFilePath.split(".");
        const fileType =
            fileTypeList.length > 1 ? `.${fileTypeList[1]}` : ".png";
        const fileSize = oldObj.tempFiles[0].size;
        const { picAll, currentPicIndex } = this.data;
        const that = this;
        const params = {
            extName: fileType,
        };
        presignedUrl(params).then((res1) => {
            const fs = wx.getFileSystemManager();
            // const payload = fs.readFileSync(res.tempFiles[0]['tempFilePath'])
            const payload = fs.readFileSync(canvasObj.tempFilePath);

            wx.request({
                url: res1.url,
                method: "PUT",
                header: {
                    "content-type": res1.headers["Content-Type"],
                },
                data: payload,
                success: (res2) => {
                    // 注意，此接口比较特殊，res2不会返回图片地址，图片地址是res1里面的url（去掉问号后面一段，只要前面一段，就是图片地址）
                    const picUrlList = res1.url.split("?");
                    let picUrl = picUrlList.length > 0 ? picUrlList[0] : "";
                    wx.hideLoading();
                    // const dataObj = JSON.parse(res.data)
                    // if (dataObj.code == 200) {
                    const newArr = that.data.picArr;
                    newArr[currentPicIndex] = picUrl;
                    picAll[currentPicIndex] = picUrl;
                    that.setData({ picArr: newArr, picAll }, () => {
                        that.checkNextTapFlag();
                    });
                    // }
                },
            });
        });
    },
    deletePic(e: baseEvent) {
        const index = e.currentTarget.dataset.index;
        let { picAll } = this.data;
        const newArr = JSON.parse(JSON.stringify(this.data.picArr));
        newArr[index] = "";
        picAll[index] = index;
        console.log(newArr);
        this.setData({ picArr: newArr, picAll }, () => {
            this.checkNextTapFlag();
        });
    },
    isShowToOthers() {
        this.setData({ showToOthersPopup: true });
    },
    closePopup() {
        this.setData({ showToOthersPopup: false });
    },
    onClosePopup() {
        const customPopup = this.selectComponent("#custom-popup");
        customPopup && customPopup.hidePopup();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {},

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {},

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {},

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {},

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {},

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {},

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {},
});
